﻿using System.Runtime.CompilerServices;
using RpcClient;
using RpcClient.Interface;
using RpcExtend.DAL;
using RpcExtend.Model.DB;
using RpcExtendModel.Trace;
using RpcHelper;
using RpcModel;

namespace RpcExtend.Collect.Collect
{
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class TraceLogCollect : ITraceLogCollect
    {
        private readonly IDelayDataSave<RpcTraceLog> _DelaySave;
        private readonly IUnityCollect _Unity;
        public TraceLogCollect(IUnityCollect unity)
        {
            this._Unity = unity;
            this._DelaySave = new DelayDataSave<RpcTraceLog>(_Save, 2, 10);
        }
        private void _Save(ref RpcTraceLog[] datas)
        {
            this._Unity.Resolve<IRpcTraceLogDAL>().Adds(datas);
        }
        public void Add(SysTraceLog log, MsgSource source)
        {
            string result = log.Args.GetValueOrDefault("Result", string.Empty);
            string msgType = log.Args.GetValueOrDefault("MsgType", string.Empty);
            log.Args.Remove("MsgType");
            log.Args.Remove("Result");
            log.Args.Remove("LocalId");
            log.Args.Remove("SystemType");
            RpcTraceLog traceLog = log.ConvertMap<SysTraceLog, RpcTraceLog>();
            traceLog.BeginTime = log.Begin;
            traceLog.EndTime = log.End;
            traceLog.MsgType = msgType;
            traceLog.RegionId = source.RegionId;
            traceLog.ServerId = log.Args.GetLong("ServerId", 0);
            traceLog.SystemType = source.SystemType;
            traceLog.ReturnRes = result;
            traceLog.Id = Tools.NewGuid();
            traceLog.ServerId = source.ServerId;
            _DelaySave.AddData(traceLog);
        }
    }
}
